import {
    makeExecutableSchema
} from 'graphql-tools';
import _ from 'lodash';
import * as home from './home';
import * as dbms from './dbms';
const modules = [home, dbms];

function pick(what) {
    return _.flatten(modules.map(
        module => _.values(_.pick(module, what))
    ));
}

const queryDefs = _.reduce(
    pick('queryDefs'), (result, def) => (result += def), ''
);
const mutationDefs = _.reduce(
    pick('mutationDefs'), (result, def) => (result += def), ''
);
const root = `
type Query {
    ${queryDefs}
}
type Mutation {
    ${mutationDefs}
}
`;

const schema = `schema {
    query: Query,
    mutation: Mutation
}
`;

let typeDefs = _.flatten(modules.map(
    module => _.values(_.pick(module, 'schema'))
));
typeDefs = [schema, root].concat(
    _.flatten(typeDefs.map(type => {
        if (typeof type === 'object') {
            return _.values(type);
        }
        return type;
    }))
);

const resolvers = {
    Query: _.reduce(pick('queries'), _.assign, {}),
    Mutation: _.reduce(pick('mutations'), _.assign, {})
};

const connectors = _.reduce(pick('connectors'), _.assign, {});

const allowUndefinedInResolve = true;

export default makeExecutableSchema({
    typeDefs, resolvers, connectors,
    allowUndefinedInResolve
});
